'use strict';

let fs = require('fs');
let path = require('path');
let router = require('koa-router')();

function searchControllersFile(dir){
   let files = fs.readdirSync(dir);
   
   return files.filter((name)=>{
       return name.endsWith('.js') && name !== 'index.js';
    })
} 


function registerControllersFile(files){
    files.forEach(item=>{
        let temPath = path.join(__dirname,item);
        let routerObj = require(temPath);

        for(let key in routerObj){
            let r = routerObj[key][0];
            let fn = routerObj[key][1];
            
            if(r === 'get'){
                router.get(key,fn);
            }else{
                router.post(key,fn);
            }
        }
    })
}


module.exports = function(dir){
    let defaultDir = dir || __dirname;

    let result = searchControllersFile(defaultDir);

    registerControllersFile(result);
    
    return router.routes();
}
